package com.hison.runner;

import com.hison.domian.entity.Article;
import com.hison.mapper.ArticleMapper;
import com.hison.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName: ViewCountRunner
 * @Descripiton: 项目启动预处理  希望在项目启动时进行一些初始化操作
 * @Author: 小郑
 * @Date： 2024/1/14 9:33
 * @Version：1.8
 **/
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisCache redisCache;


    @Override
    public void run(String... args) throws Exception {
//        查询博客信息  id   viewCount
        List<Article> articleList = articleMapper.selectList(null);
        Map<String, Integer> viewCountMap = articleList.stream().collect(Collectors.toMap(new Function<Article, String>() {
            @Override
            public String apply(Article article) {

                return article.getId().toString();
            }
        }, new Function<Article, Integer>() {
            @Override
            public Integer apply(Article article) {
                return article.getViewCount().intValue();
            }
        }));

        //存储到redis中
        redisCache.setCacheMap("article:viewCount",viewCountMap);
    }
}